package show.me.the.money.util.exp.standard;

import java.util.List;

import show.me.the.money.util.context.Context;
import show.me.the.money.util.exp.ExpRunner;
import show.me.the.money.util.exp.ExpSymbols;
import show.me.the.money.util.exp.Expression;

@SuppressWarnings("unchecked")
public class IN extends Expression {
	public Object run(List lsExp, Context ctx) {
		boolean b = false;
		try {
			List la1 = (List)lsExp.get(1);
			String s1 = String.valueOf((ExpRunner.run(la1, ctx)));
			List la2 = (List)lsExp.get(2);
			for(Object o : la2){
				String s2 = String.valueOf(o);
				if(s1.equals(s2)){
					b = true;
					break;
				}
			}
		} 
		catch (Exception e) {
			logger.fatal("run JSONException:", e);
		}
		return b;
	}

	public String toString(List lsExp, Context ctx) {
		StringBuffer expr = new StringBuffer();
		try {
			List la1 = (List)lsExp.get(1);
			String s1 = ExpRunner.toString(la1, ctx);
			expr.append(s1).append(" ").append(ExpSymbols.IN).append(" (");
			List la2 = (List)lsExp.get(2);
			
			boolean isString = true;
			if(lsExp.size() > 3){
				String type = (String)lsExp.get(3);
				if ("d".equals(type)) {
					isString = false;
				}
			}
			int n = la2.size();
			for (int i = 0; i < n; i++) {
				String s = String.valueOf(la2.get(i));
				if (isString) {
					expr.append("'").append(s).append("'");
				} 
				else{
					expr.append(s);
				}
				expr.append(",");
			}
			expr.setLength(expr.length() - 1);
			expr.append(")");
			return expr.toString();
		} 
		catch (Exception e) {
			logger.fatal("run JSONException:", e);
		}
		return "";
	}

}
